import { login, getPermission } from "@/api/api";
import { setItem, getItem, removeAllItem } from "@/utils/storage";
import { TOKEN, USERINFO } from "@/constant";
import { setTimeStamp } from "@/utils/auth";
import { formatPermissionList, lowerCase } from "@/utils/index";
import router, { resetRouter } from "@/router";
import { ElMessage } from "element-plus";
import { localPermissionData } from "@/constant/local-permission";

export default {
	namespaced: true,
	state: () => ({
		// token的初始值从storage里取
		token: getItem(TOKEN) || "",
		userInfo: getItem(USERINFO) || {},
		roles: [],
		buttons: []
	}),
	mutations: {
		setToken(state, token) {
			state.token = token;
			setItem(TOKEN, token);
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo;
			setItem(USERINFO, userInfo);
		},
		setRoles: (state, roles) => {
			state.roles = roles;
		},
		setButtons: (state, buttons) => {
			state.buttons = buttons;
		}
	},
	actions: {
		login(context, userInfo) {
			return new Promise((resolve, reject) => {
				login(userInfo)
					.then(data => {
						console.log("登录返回数据", data);
						// 兼容后端返回结构：有 code=200 或 status.error_code=0
						let user = null;
						let token = "";
						let admin_nick_name = "";
						let admin_id = "";
						let avatar = "";
						console.log("userInfo", data.code);
						if (data && data.code == 200 && data.data) {
							// 后端返回 { code: 200, data: {...} }
							user = Array.isArray(data.data) ? data.data[0] : data.data;
							token = user.Token || user.sys_token || "mock_token";
							admin_nick_name = user["员工姓名"] || user["登录账号"] || user.admin_nick_name || "";
							admin_id = user["员工ID"] || user.admin_id || "";
							avatar = user.avatar || "";
						} else if (data && data.status && data.status.error_code === 0 && data.obj) {
							// mock结构 { status: {error_code:0}, obj: {...} }
							user = data.obj;
							token = user.sys_token || "mock_token";
							admin_nick_name = user.admin_nick_name || "";
							admin_id = user.admin_id || "";
							avatar = user.avatar || "";
						}
						if (token) {
							const obj = {
								sys_token: token,
								admin_nick_name,
								admin_id,
								avatar
							};
							this.commit("user/setToken", obj.sys_token);
							this.commit("user/setUserInfo", obj);
							setTimeStamp();
							resolve(data);
						} else {
							ElMessage.error("登录失败");
							reject("登录失败");
						}
					})
					.catch(err => {
						ElMessage.error("网络异常");
						reject(err);
					});
			});
		},
		getPermissionData(context) {
			return new Promise((resolve) => {
				// 直接使用本地权限数据并格式化
				const obj = formatPermissionList(localPermissionData);
				const role_arr = obj.role_arr;
				const button_arr = obj.button_arr;
				const info = {
					roles: role_arr
				};
				context.commit("setRoles", role_arr);
				context.commit("setButtons", button_arr);
				resolve(info);
			});
		},
		logout() {
			resetRouter();
			this.commit("user/setToken", "");
			this.commit("user/setUserInfo", {});
			this.commit("user/setRoles", []);
			this.commit("user/setButtons", []);
			this.commit("app/removeTagsView", {
				type: "all"
			});
			// 只清除登录相关，不清除记住密码
			const remember = localStorage.getItem('remember');
			const remember_username = localStorage.getItem('remember_username');
			const remember_password = localStorage.getItem('remember_password');
			removeAllItem();
			if (remember === 'true') {
				localStorage.setItem('remember', remember);
				localStorage.setItem('remember_username', remember_username);
				localStorage.setItem('remember_password', remember_password);
			}
			router.push("/login");
		}
	}
};